<!-- 公共组件页面 -->
<template>
  <view class="publicPage">
    <!-- 内容高度 -->
    <view
      :style="`min-height: ${sys.windowHeight}px;background-color: ${bgColor};`">
      <slot></slot>
    </view>
  </view>
</template>

<script setup lang="ts">
import { useMsgStore } from "@/stores/msg";

const sys = uni.$u.sys() as any // 设备信息
const props = defineProps({
  // 内容主体颜色
  bgColor: {
    type: String,
    default: '#FFFFFF'
  }
})

function objectToUrlParams(obj: Record<string, any>): string {
  if (Object.keys(obj).length === 0) {
    return '';
  }
  const querys = Object.entries(obj).map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`);
  return querys.join('&')
}

const { linkWebSocket } = useMsgStore();
onLoad(() => {
  // 实现简易页面拦截, 实现路由跳转拦截,需在uview中的uni.$u.routeIntercept注册拦截器
  const pageUrl = uni.$u.page();
  const token = uni.getStorageSync('token');

  if(pageUrl === `/pages/login/login` && token){// 已登录,不允许再次登录
    uni.$u.route({
      type: 'navigateBack',
      delta: 1
    })
  }else if(pageUrl !== `/pages/login/login` && !token){ // 未登录,拦截其它页面
    const pages = uni.$u.pages();
    const query = pages[pages.length - 1].options;
    uni.$u.route({
      type: 'reLaunch',
      url: '/pages/login/login',
      params: {
        callBackPage: pageUrl + '?' + objectToUrlParams(query)
      }
    })
  }

  linkWebSocket()
})
</script>
